package logic

import (
	"2211a_mayi/service/cache"
	"2211a_mayi/service/models"
	"context"
	"errors"

	"2211a_mayi/service/internal/svc"
	"2211a_mayi/service/mayi"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCartLogic) AddCart(in *mayi.AddCartRequest) (*mayi.AddCartResponse, error) {
	// 商品是否存在
	var g models.Goods
	var err error
	err = g.Detail(int(in.GoodsId))
	if err != nil {
		logx.Error(err)
		return nil, err
	}
	// 库存是否充足
	if g.GoodsStock < int(in.Num) {
		logx.Error("库存不足")
		return nil, errors.New("库存不足")
	}
	// 购物车数据
	cartMap := map[string]interface{}{
		"user_id":     in.UserId,
		"goods_id":    in.GoodsId,
		"goods_title": g.GoodsTitle,
		"goods_desc":  g.GoodsDesc,
		"goods_cover": g.GoodsCover,
		"goods_price": g.GoodsPrice,
		"num":         in.Num,
		"checked":     1,
	}

	// 购物车是否存在
	num := cache.CartNum(int(in.UserId), int(in.GoodsId))
	if num > 0 {
		// 如果存在则更新数量，查看当前数量
		cartMap["num"] = int(in.Num) + num
	}

	if cache.SaveCart(int(in.UserId), int(in.GoodsId), cartMap) != nil {
		logx.Error(err)
		return nil, err
	}

	return &mayi.AddCartResponse{}, nil
}
